package cn.jjxx.modules.portal.controller;

import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.common.jcaptcha.JCaptcha;
import cn.jjxx.modules.portal.utils.MessageConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * jsp验证码
 * @author mali
 */
@Controller
@RequestMapping("/portal/captcha")
public class JCaptchaController {

    /**
     * 获取jsp验证码
     * @param request req
     * @param response rep
     * @param type 类型，该类型会与sessionId一起作为验证码的ID
     * @throws IOException ioexception
     * @author mali
     * @date 2020-02-12
     */
    @RequestMapping(value = "getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response, String type) throws IOException {

        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String id = request.getRequestedSessionId();
        BufferedImage bi = null;
        if (StringUtils.isNotBlank(type)) {
            bi = JCaptcha.captchaService.getImageChallengeForID(id + type);
        } else {
            bi = JCaptcha.captchaService.getImageChallengeForID(id);
        }

        ServletOutputStream out = response.getOutputStream();

        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    /**
     * 前端jsp验证码在线验证接口，验证完会删除缓存中的验证码
     * @param request req
     * @param response rep
     * @param type 类型，该类型会与sessionId一起作为验证码的ID
     * @param jCaptchaCode 前端输入的验证码
     * @return json
     * @author mali
     * @date 2020-02-12
     */
    @RequestMapping(value = "validate")
    @ResponseBody
    public AjaxJson validate(HttpServletRequest request, HttpServletResponse response, String type, String jCaptchaCode) {
        AjaxJson result = new AjaxJson();

        String sessionId = request.getRequestedSessionId();
        String captchaId = sessionId;
        if (StringUtils.isNotBlank(type)) {
            captchaId = captchaId + type;
        }
        boolean validate = JCaptcha.validateResponse(request, captchaId, jCaptchaCode);
        if (validate) {
            result.success(MessageConfig.J_CAPTCHA_SUCCESS);
        } else {
            result.fail(MessageConfig.J_CAPTCHA_ERROR);
        }

        return result;
    }
}
